//
//  DetailViewController.m
//  THD
//
//  Created by CA on 14-5-15.
//  Copyright (c) 2014年 CA. All rights reserved.
//

#import "SearchViewController.h"
#import "CommunicationManager.h"
#import "DeviceCell.h"
#import "ArrayDataSource.h"
#import "LGBluetooth.h"

static NSString * const kDeviceCellIndentifier = @"DeviceCell";

@interface SearchViewController () <UIGestureRecognizerDelegate, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *popView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *spinner;
@property (weak, nonatomic) IBOutlet UIButton *connectButton;
@property (weak, nonatomic) IBOutlet UILabel *titleDescriptionLabel;
@property (nonatomic, strong) ArrayDataSource *deviceArrayDataSource;
@end

@implementation SearchViewController
{
    __block BOOL _shouldRefresh;
}

#pragma mark - View LifeCycle

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _shouldRefresh = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self configureLocalization];
    [self addGestureRecognizer];
    [self configureSearchView];
    [self registerNotification];
    [self updateThemeUI];
    [self.tableView registerNib:[DeviceCell nib] forCellReuseIdentifier:kDeviceCellIndentifier];
    [self setupTableView];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Notification

- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshRssi:) name:kLGCentralManagerDidRefreshRssiNotification object:nil];
}

- (void)handleRefreshRssi:(NSNotification *)notification
{
    if (_shouldRefresh) {
        _shouldRefresh = NO;
        
        self.lgPeripherals = [self.lgPeripherals sortedArrayUsingComparator:^NSComparisonResult(LGPeripheral *obj1, LGPeripheral *obj2) {
            return obj1.countOfSignal < obj2.countOfSignal;
        }];
        
        [self setupTableView];
        [self.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _shouldRefresh = YES;
        });
    }
}

#pragma mark - IBAction

- (IBAction)connectPeripheral:(UIButton *)sender
{
    LGPeripheral *peripheral = [self selectedPeripheral];
    if (peripheral != nil) {
        [self connectThePeripheral:peripheral];
    }
}

#pragma mark - UIGestureRecognizer Delegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return (touch.view == self.view);
}

#pragma mark - Private Method

- (void)setupTableView
{
    TableViewCellConfigureBlock configureCellBlock = ^(DeviceCell *cell, LGPeripheral *peripehral) {
        [cell configureWithPeirpheral:peripehral];
    };
    
    self.deviceArrayDataSource = [[ArrayDataSource alloc] initWithItems:self.lgPeripherals cellIdentifier:kDeviceCellIndentifier configureCellBlock:configureCellBlock];
    self.tableView.dataSource = self.deviceArrayDataSource;
}

- (void)configureLocalization{
    self.titleDescriptionLabel.text = NSLocalizedString(@"Please select your device", nil);
    [self.connectButton setTitle:NSLocalizedString(@"Connect", nil) forState:UIControlStateNormal];
}

- (void)updateThemeUI
{
    self.popView.backgroundColor = kSearchViewBackgroundColor;
    self.connectButton.backgroundColor = kSearchViewBackgroundColor;
    self.connectButton.layer.cornerRadius = 5;
    self.connectButton.layer.borderColor = [UIColor colorWithHex:0x7c7b80 alpha:0.5].CGColor;
    self.connectButton.layer.borderWidth = 1;
}

- (void)configureSearchView
{
    self.popView.layer.cornerRadius = 10.0f;
    self.connectButton.layer.cornerRadius = 3.0f;
    self.view.backgroundColor = [UIColor clearColor];
    self.tableView.separatorColor = [UIColor colorWithWhite:1.0f alpha:0.5f];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    
    UINib *nibCell = [UINib nibWithNibName:kDeviceCellIndentifier bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:kDeviceCellIndentifier];
}

- (void)close
{
    [[LGCentralManager sharedInstance] stopScanForPeripherals];
    [self.spinner stopAnimating];
    
    [self dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeFade];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchViewControllerDidDismissFromParentViewController:)]) {
        [self.delegate searchViewControllerDidDismissFromParentViewController:self];
    }
}

- (void)addGestureRecognizer
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    gestureRecognizer.cancelsTouchesInView = NO;
    gestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:gestureRecognizer];
}

- (void)updateUI
{
    [self.tableView reloadData];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self didMoveToParentViewController:self.parentViewController];
    [self.spinner startAnimating];
    if (self.lgPeripherals == nil) {
        [[LGCentralManager sharedInstance] scanForPeripheralsWithScanBlock:^(NSArray *peripherals) {
            self.lgPeripherals = peripherals;
            [self setupTableView];
            [self.tableView reloadData];
        }];
    }
}

- (void)cancelAllPeripheralSelected
{
    for (LGPeripheral *peripheral in self.lgPeripherals) {
        peripheral.isSelected = NO;
    }
}

// 所选择的设备，有的话返回当前设备
- (LGPeripheral *)selectedPeripheral
{
    if ([self.lgPeripherals count] > 0) {
        for (LGPeripheral *peripheral in self.lgPeripherals) {
            if (peripheral.isSelected) {
                return peripheral;
            }
        }
    }
    
    return nil;
}

#pragma mark - Private Method

- (void)connectThePeripheral:(LGPeripheral *)peripheral
{
    __weak SearchViewController *weakSelf = self;
    
    [weakSelf close];
    
    MBProgressHUD *hud = nil;
    
    if (self.tabBarController != nil) {
        hud = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES];
    } else {
        hud = [MBProgressHUD showHUDAddedTo:self.parentViewController.view animated:YES];
    }
    
     hud.label.text =  NSLocalizedString(@"Connecting", nil);
     [hud hideAnimated:YES afterDelay:5.0];
    
    [peripheral connectWithCompletion:^(NSError *error) {
        
        if (!error) {
            
            [[CommunicationManager shareInstance] setupServicesWithPeripheral:peripheral completion:^(BOOL success) {
                hud.label.text = success ? NSLocalizedString(@"Connected", nil) : NSLocalizedString(@"Connection fail", nil);
                [hud hideAnimated:YES afterDelay:1.0];
                
                if (success && self.delegate && [self.delegate respondsToSelector:@selector(searchViewControllerDidConnectPeripheral:)]) {                    
                    
                    [[RLMRealm defaultRealm] beginWriteTransaction];
                    User *user = [User getLastUser];
                    user.userDevice.deviceUUID = peripheral.UUIDString;
                    user.userDevice.oemType = peripheral.oemType;
                    [[RLMRealm defaultRealm] commitWriteTransaction];
                    
                    [self.delegate searchViewControllerDidConnectPeripheral:self];
                    YFSensorApi *api = [YFSensorApi initWithOemType:peripheral.oemType derviceMac:peripheral.macAddress derviceName:peripheral.name];
                    
                    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
                        if (success) {
                            NSLog(@"发送设备信息成功");
                        }
                    }];
                }
            }];
            
        } else {
            hud.label.text = NSLocalizedString(@"Connection fail", nil);
            [hud hideAnimated:YES afterDelay:1.0];
        }
        
    }];
}

#pragma mark - UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    for (NSInteger i = 0; i < self.lgPeripherals.count ; i++) {
        DeviceCell * cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        [cell configureDeviceNameLabelTextColor:kUnSelectedColor];
        if (indexPath.row == i) {
            [cell configureDeviceNameLabelTextColor:kSelectedColor];
        }
    }
    self.connectButton.layer.borderColor = kSelectedColor.CGColor;
    [self.connectButton setTitleColor:kSelectedColor forState:UIControlStateNormal];
    
    [self cancelAllPeripheralSelected];
    
    // 选取当前的设备
    LGPeripheral *peripheral = [self.deviceArrayDataSource itemAtIndexPath:indexPath];
    peripheral.isSelected = YES;

    [self.tableView reloadData];
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.highlightedTextColor = cell.textLabel.textColor;
    
    UIView *selectionView = [[UIView alloc] initWithFrame:CGRectZero];
    selectionView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.2f];
    cell.selectedBackgroundView = selectionView;
}


@end
